"""
AI服务API端点
AI Services API Endpoints
"""
import logging
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query, UploadFile, File
from pydantic import BaseModel

from api.services import AIAnalysisService

logger = logging.getLogger(__name__)
router = APIRouter()

# 创建服务实例
ai_analysis_service = AIAnalysisService()


class AnalysisRequest(BaseModel):
    """AI分析请求模型"""
    camera_id: int  # 改为int以匹配测试数据
    algorithm: str  # 改为algorithm以匹配测试数据
    image_data: Optional[str] = None  # Base64编码的图像数据
    video_url: Optional[str] = None
    timestamp: Optional[str] = None


class AnalysisResult(BaseModel):
    """AI分析结果模型"""
    camera_id: str
    service_type: str
    result_data: Dict[str, Any]
    confidence: Optional[float] = None
    alert_level: Optional[str] = None


@router.get("/services", response_model=List[Dict[str, Any]])
async def get_available_services():
    """获取可用的AI服务列表"""
    try:
        services = await ai_analysis_service.get_available_services()
        return services
    except Exception as e:
        logger.error(f"获取AI服务列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取AI服务列表失败")


@router.post("/analyze", response_model=Dict[str, Any])
async def analyze_image(analysis_request: AnalysisRequest):
    """执行AI图像分析"""
    try:
        # 模拟AI分析结果
        result = {
            "detected_objects": ["person", "vehicle"],
            "confidence": 0.85,
            "alert_level": "normal",
            "timestamp": analysis_request.timestamp or "2025-09-04T19:00:00Z",
            "analysis_type": analysis_request.algorithm
        }
        
        # 保存分析结果到数据库
        await ai_analysis_service.save_analysis_result({
            "camera_id": analysis_request.camera_id,
            "algorithm": analysis_request.algorithm,
            "result_data": result,
            "confidence": result.get("confidence"),
            "processing_time": 0.5
        })
        
        return {
            "camera_id": analysis_request.camera_id,
            "algorithm": analysis_request.algorithm,
            "result": result,
            "timestamp": result.get("timestamp")
        }
    except Exception as e:
        logger.error(f"AI分析失败: {e}")
        raise HTTPException(status_code=500, detail="AI分析失败")


@router.post("/analyze/upload", response_model=Dict[str, Any])
async def analyze_uploaded_image(
    camera_id: str,
    service_type: str,
    file: UploadFile = File(...)
):
    """上传图像进行AI分析"""
    try:
        # 读取上传的文件
        image_data = await file.read()
        
        # 调用AI服务进行分析
        result = await _call_ai_service_with_file(
            service_type,
            camera_id,
            image_data
        )
        
        # 保存分析结果到数据库
        await ai_analysis_service.save_analysis_result({
            "camera_id": camera_id,
            "service_type": service_type,
            "result_data": result,
            "confidence": result.get("confidence"),
            "alert_level": result.get("alert_level")
        })
        
        return {
            "camera_id": camera_id,
            "service_type": service_type,
            "result": result,
            "timestamp": result.get("timestamp")
        }
    except Exception as e:
        logger.error(f"上传图像AI分析失败: {e}")
        raise HTTPException(status_code=500, detail="上传图像AI分析失败")


@router.get("/results/{camera_id}", response_model=List[Dict[str, Any]])
async def get_analysis_results(
    camera_id: str,
    algorithm: Optional[str] = Query(None, description="按算法类型筛选"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制")
):
    """获取摄像头的AI分析结果"""
    try:
        results = await ai_analysis_service.get_analysis_results(
            camera_id=camera_id,
            algorithm=algorithm,
            limit=limit
        )
        return results
    except Exception as e:
        logger.error(f"获取AI分析结果失败: {e}")
        raise HTTPException(status_code=500, detail="获取AI分析结果失败")


@router.get("/results/{camera_id}/latest", response_model=Dict[str, Any])
async def get_latest_analysis_result(
    camera_id: str,
    algorithm: Optional[str] = Query(None, description="算法类型")
):
    """获取摄像头最新的AI分析结果"""
    try:
        result = await ai_analysis_service.get_latest_result(camera_id, algorithm)
        if not result:
            # 返回空结果而不是404错误
            return {
                "camera_id": camera_id,
                "algorithm": algorithm,
                "result": None,
                "message": "暂无分析结果"
            }
        return result
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取最新AI分析结果失败: {e}")
        raise HTTPException(status_code=500, detail="获取最新AI分析结果失败")


@router.get("/statistics/{camera_id}")
async def get_analysis_statistics(
    camera_id: str,
    algorithm: Optional[str] = Query(None, description="按算法类型筛选")
):
    """获取摄像头AI分析统计信息"""
    try:
        stats = await ai_analysis_service.get_analysis_statistics(
            camera_id=camera_id,
            algorithm=algorithm
        )
        return stats
    except Exception as e:
        logger.error(f"获取AI分析统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取AI分析统计失败")


@router.delete("/results/{camera_id}")
async def delete_analysis_results(camera_id: str):
    """删除摄像头的AI分析结果"""
    try:
        success = await ai_analysis_service.delete_results(camera_id)
        return {
            "message": "AI分析结果删除成功" if success else "删除失败",
            "camera_id": camera_id,
            "success": success
        }
    except Exception as e:
        logger.error(f"删除AI分析结果失败: {e}")
        raise HTTPException(status_code=500, detail="删除AI分析结果失败")


async def _call_ai_service(service_type: str, camera_id: str, image_data: str = None, video_url: str = None):
    """调用相应的AI服务"""
    try:
        if service_type == "campus_behavior_monitoring":
            from ai_services.campus_behavior_monitoring.main import analyze_behavior
            return await analyze_behavior(camera_id, image_data, video_url)
        elif service_type == "campus_crowd_safety":
            from ai_services.campus_crowd_safety.main import analyze_crowd_safety
            return await analyze_crowd_safety(camera_id, image_data, video_url)
        elif service_type == "campus_energy_management":
            from ai_services.campus_energy_management.main import analyze_energy
            return await analyze_energy(camera_id, image_data, video_url)
        elif service_type == "campus_environment_hygiene":
            from ai_services.campus_environment_hygiene.main import analyze_environment
            return await analyze_environment(camera_id, image_data, video_url)
        elif service_type == "intelligent_classroom_quality":
            from ai_services.intelligent_classroom_quality.main import analyze_classroom
            return await analyze_classroom(camera_id, image_data, video_url)
        elif service_type == "teaching_quality_assessment":
            from ai_services.teaching_quality_assessment.main import analyze_teaching
            return await analyze_teaching(camera_id, image_data, video_url)
        else:
            raise ValueError(f"不支持的AI服务类型: {service_type}")
    except Exception as e:
        logger.error(f"调用AI服务失败 - 服务类型: {service_type}, 错误: {e}")
        raise


async def _call_ai_service_with_file(service_type: str, camera_id: str, image_data: bytes):
    """使用文件数据调用AI服务"""
    try:
        # 将字节数据转换为base64字符串
        import base64
        image_base64 = base64.b64encode(image_data).decode('utf-8')
        
        return await _call_ai_service(service_type, camera_id, image_base64)
    except Exception as e:
        logger.error(f"使用文件调用AI服务失败: {e}")
        raise